package com.hlt360.benchmark;

import com.lanyuan.entity.UserFormMap;
import com.lanyuan.util.Common;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Component
@Aspect
@Order(2)
public class BenchmarkAopAction {

    @Pointcut("execution(public * com.lanyuan.controller..*.*(..))")
    public void controllerAspect() {
    }

    @Around("controllerAspect()")
    public Object doController(ProceedingJoinPoint point) throws Throwable {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        try {
            return point.proceed();
        } finally {
            HttpServletRequest request = getRequest();
            String prompt = request == null ? "Benchmark> EMPTY URI - " : "Benchmark> " + request.getRequestURI() + " - ";
            String message = "User[" + getUserAccountName() + "]";
            stopWatch.stop();
            if (stopWatch.getTime() > 100) {
                log.warn(prompt + stopWatch.getTime() + "ms" + " - " + message);
            } else {
                log.info(prompt + stopWatch.getTime() + "ms" + " - " + message);
            }
        }
    }

    private HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    private String getUserAccountName() {
        HttpServletRequest request = getRequest();
        try {
            if (request != null) {
                UserFormMap userFormMap = (UserFormMap) Common.findUserSession(request);
                if (userFormMap != null) {
                    return userFormMap.getStr("accountName");
                }
            }
        } catch (Exception e) {

        }
        return null;
    }

}
